package com.ultrawise.survey.common;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.rowset.ResultSetWrappingSqlRowSetMetaData;

import com.ultrawise.survey.common.utils.ReflectionUtils;

public class DAORowMapper implements RowMapper {
	private Class rowObjectClass;
	
	public DAORowMapper(Class rowObjectClass){
		this.rowObjectClass = rowObjectClass;
	}
	
    public Object mapRow(ResultSet rs, int index) throws SQLException {
        Object object;
		try {
			object = rowObjectClass.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		ResultSetWrappingSqlRowSetMetaData wapping = new ResultSetWrappingSqlRowSetMetaData(rs.getMetaData());
		for(int i=1;i<=wapping.getColumnCount();i++){
			String name = wapping.getColumnName(i);
			Object value = rs.getObject(i);
			ReflectionUtils.setFieldVlaue(object, name, value);
		}

        return object;
    }

}
